package com.wfm.leetcode.editor.cn;

import com.wfm.common.ListNode;

import java.util.HashSet;
import java.util.Set;

/**
 * 环形链表
 * 2025-02-26 15:06:29
 *  方法1：用map记录是否访问过
 *  方法2：快慢指针
 */
class LinkedListCycle {

    //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        Set<ListNode> s = new HashSet<>();
        while (head!=null){
            if(!s.add(head)){
                return true;
            }
            head=head.next;
        }
        return false;
    }

    public boolean hasCycle2(ListNode head) {
        if(head==null||head.next==null){
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (slow!=fast){
            if(fast==null||fast.next==null) return false;
            slow=slow.next;
            fast=fast.next.next;
        }
        return true;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

    public static void main(String[] args) {
        Solution solution = new LinkedListCycle().new Solution();
        
    }
}